package com.tx.admin.core.anno.aop;

import java.lang.reflect.Method;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import com.tx.admin.core.anno.Log;
import com.tx.admin.modules.base.entity.LogEntity;
import com.tx.admin.modules.base.repository.LogRepository;
import com.tx.admin.util.common.AopUtil;
import com.tx.admin.util.common.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Component
@Aspect
@Slf4j
public class LogAop {


	
	@Autowired
	private LogRepository logRepository;
	
	@Pointcut("@annotation(com.tx.admin.core.anno.Log)")
	public void aop() {
			
	}
	
	
	
	@Around("aop()")  
	public Object doAroundAdvice(ProceedingJoinPoint pjp) throws Throwable{  
		Object val = pjp.proceed();

		MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method method = ms.getMethod();
        Log log = AnnotationUtils.findAnnotation(method, Log.class); 
        Map<String,Object> params = AopUtil.getParams(pjp);
        params.put("#val", val);
  
        String title =  StringUtil.render(log.title(), params);
        String content =  StringUtil.render(log.content(), params);
        LogEntity logEntity = new LogEntity();
        logEntity.setTitle(title);
        logEntity.setContent(content);
     
        logRepository.save(logEntity);
        return val;
	}
	  
}
